window.addEventListener('DOMContentLoaded', function () {
  function animate(obj, target, callback) {
    clearInterval(obj.timer)
    obj.timer = setInterval(function () {
      var step = (target - obj.offsetLeft) / 10
      step = step > 0 ? Math.ceil(step) : Math.floor(step)
      if (obj.offsetLeft === target) {
        clearInterval(obj.timer)
        callback && callback()
      }
      obj.style.left = obj.offsetLeft + step + 'px'
    }, 15)
  }
  var focus = document.querySelector('.focus')
  var arrowl = document.querySelector('.arrow-l')
  var arrowr = document.querySelector('.arrow-r')
  var ul = focus.querySelector('ul')
  var ol = focus.querySelector('ol')
  var focusWidth = focus.offsetWidth
  console.log(focusWidth)
  focus.addEventListener('mouseenter', function () {
    arrowl.style.display = 'block'
    arrowr.style.display = 'block'
    clearInterval(timer)
    timer = null
  })
  focus.addEventListener('mouseleave', function () {
    arrowl.style.display = 'none'
    arrowr.style.display = 'none'
    clearInterval(timer)
    timer = setInterval(function () {
      arrowr.click()
    }, 3000)
  })
  for (var i = 0; i < ul.children.length; i++) {
    var li = document.createElement('li')
    ol.appendChild(li)
    li.setAttribute('index', i)
    li.addEventListener('click', function () {
      for (var i = 0; i < ol.children.length; i++) {
        ol.children[i].className = ''
      }
      this.className = 'current'
      var index = this.getAttribute('index')
      num = circle = index
      animate(ul, -index * focusWidth)
    })
  }
  ol.children[0].className = 'current'
  var first = ul.children[0].cloneNode(true)
  ul.appendChild(first)
  var num = 0
  var circle = 0
  var flag = true
  arrowr.addEventListener('click', function () {
    if (flag) {
      flag = false
      if (num >= ul.children.length - 1) {
        num = 0
        ul.style.left = 0
      }
      num++
      animate(ul, -num * focusWidth, function () {
        flag = true
      })
      circle++
      circle = circle >= ol.children.length ? 0 : circle
      circleChange()
    }
  })
  arrowl.addEventListener('click', function () {
    if (flag) {
      flag = false
      if (num === 0) {
        num = ul.children.length - 1
        ul.style.left = -num * focusWidth + 'px'
      }
      num--
      animate(ul, -num * focusWidth, function () {
        flag = true
      })
      circle--
      circle = circle < 0 ? ol.children.length - 1 : circle
      circleChange()
    }
  })
  var timer = setInterval(function () {
    arrowr.click()
  }, 2000)

  function circleChange() {
    for (var i = 0; i < ol.children.length; i++) {
      ol.children[i].className = ''
    }
    ol.children[circle].className = 'current'
  }
})
